package spring.cloud.tasks.api.analyzer;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import spring.cloud.tasks.api.domain.executor.Executor;
import spring.cloud.tasks.api.domain.executor.ExecutorStatus;
import spring.cloud.tasks.api.domain.zooKeeperClusterAndNameSpace.NameSpaceConfiguration;
import spring.cloud.tasks.api.service.TaskService;
import spring.cloud.tasks.common.zookeeper.ZooKeeper;

import java.util.List;

@Slf4j
@Setter
@Getter
public class UnableHaTaskAnalyzer {


    private TaskService taskService;

    /**
     * 查找无法高可用的任务
     */
    public void analyzeUnableHaJob(ZooKeeper zooKeeper, NameSpaceConfiguration nameSpaceConfiguration, List<UnableHaTask> unableHaTaskList, String taskId) {
        UnableHaTask unableHaTask = new UnableHaTask(nameSpaceConfiguration.getNameSpace(), taskId);
        if (isUnableHa(zooKeeper, unableHaTask)) {
            unableHaTaskList.add(unableHaTask);
        }
    }

    /**
     * 无法高可用的情况： 1、勾选只使用优先executor，preferList只有一个物理机器（剔除offline、deleted的物理机） 2、没有勾选只使用优先executor，没有选择容器资源，可供选择的preferList只有一个物理机器（剔除offline、deleted的物理机，剔除容器资源）
     */
    private boolean isUnableHa(ZooKeeper zooKeeper, UnableHaTask unableHaTask) {
        try {
            String taskId = unableHaTask.getTaskId();
            List<Executor> executorList = taskService.getExecutorList(zooKeeper.getCuratorFramework().getNamespace(), taskId);
            if (CollectionUtils.isEmpty(executorList)) {
                return false;
            }
            int count = 0;
            for (Executor executor : executorList) {
                if (ExecutorStatus.ONLINE.equals(executor.getExecutorStatus())) {
                    count++;
                }
                if (count > 1) {
                    break;
                }
            }
            return count <= 1;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return true;
        }
    }


}
